import openai
import requests
import json

#Changing the OPENAI to request



# Initialize the OpenAI API key
openai.api_key = "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"

# Initialize messages for chat functionality
messages = [{"role": "system", "content": "You are a helpful assistant."}]

# Function to handle image generation
def generate_image(image_prompt):
    try:
        # Send a request to OpenAI's image generation API
        response = openai.Image.create(
            prompt=image_prompt,
            n=1,  # Number of images to generate
            size="1024x1024"  # Image size options: "256x256", "512x512", "1024x1024"
        )
        # Extract the image URL from the response
        image_url = response['data'][0]['url']
        print("Image URL:", image_url)
    except Exception as e:
        print(f"Error generating image: {e}")

# Function to handle chat completion
def generate_chat_response(user_input):
    # Add the user's input to the message history
    messages.append({"role": "user", "content": user_input})

    try:
        # Send a request to OpenAI's chat API
        response = openai.ChatCompletion.create(
            model="gpt-4",  # Model to use for chat
            messages=messages
        )

        # Get the assistant's response from the API response
        assistant_response = response['choices'][0]['message']['content']

        # Print the assistant's response
        print("Assistant:", assistant_response)

        # Add the assistant's response to the message history
        messages.append({"role": "assistant", "content": assistant_response})

    except Exception as e:
        print(f"Error generating chat response: {e}")

# Main loop
while True:
    # Read the next prompt from the user
    user_input = input("You: ")

    # Exit the loop if the user types 'exit'
    if user_input.lower() == 'exit':
        print("Exiting the chat.")
        break

    # Check if the user wants to generate an image
    if user_input.lower().startswith("generate image"):
        image_prompt = user_input[len("generate image"):].strip()
        generate_image(image_prompt)

    # Otherwise, handle the chat functionality
    else:
        generate_chat_response(user_input)
